package com.topdt.jbpm.web.struts.action;

import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.thx.common.struts2.CurdAction;
import com.thx.common.util.AppContext;
import com.thx.log.LogUtil;
import com.topdt.jbpm.identity.Department;
import com.topdt.jbpm.identity.IdFactory;
import com.topdt.jbpm.identity.IdentityService;
import com.topdt.jbpm.identity.Role;
import com.topdt.jbpm.identity.User;
import com.topdt.jbpm.model.AppAuthority;
import com.topdt.jbpm.model.AppType;
import com.topdt.jbpm.model.Application;
import com.topdt.jbpm.model.Work;
import com.topdt.jbpm.service.AppAuthorityService;
import com.topdt.jbpm.service.AppTypeService;
import com.topdt.jbpm.service.ApplicationService;
import com.topdt.jbpm.service.AttachmentService;
import com.topdt.jbpm.service.HistTodoService;
import com.topdt.jbpm.service.TodoService;
import com.topdt.jbpm.service.WorkService;
import com.topdt.jbpm.utils.ModuleConstant;
import com.topdt.jbpm.web.SessionUserUtil;

@Namespace(value = "/workflow")
@Action(value = "mywork",
		results = {
		@Result(name = "ticketShow", location = "/workflow/myWork/myWork.jsp"),
		@Result(name = "docShow", location = "/workflow/myWork/myDoc.jsp"),
		@Result(name = "ticketShow_oneApp", location = "/workflow/myWork/myWork_oneApp.jsp"),
		@Result(name = "ticketShow_Lending", location = "/workflow/myWork/myWork_lending.jsp"),
		@Result(name = "docShow_oneApp", location = "/workflow/myWork/myDoc_oneApp.jsp"),
		@Result(name = "showOfficeDocByTypes", location = "/workflow/myWork/myDoc_someTypes.jsp"),
		@Result(name = "list", location = "/workflow/draft/list.jsp"),
		@Result(name = "list_oneApp", location = "/workflow/draft/list_oneApp.jsp"),
		@Result(name = "list_lending", location = "/workflow/draft/list_lending.jsp"),
		@Result(name = "delete", type="redirect", location = "mywork!list.action",params={"appId","${appId}","entity.workState","${entity.workState}","expand","${expand}","entity.workType","${entity.workType}","officeDocTypeAppIds","${officeDocTypeAppIds}"}),
		@Result(name = "delete_oneApp", type="redirect", location = "mywork!doListByAppId.action",params={"appId","${appId}","entity.workState","${entity.workState}","expand","${expand}","entity.workType","${entity.workType}","locationFlag","${locationFlag}","appName","${appName}"})
		},
		interceptorRefs = {
		@InterceptorRef("topDtStack"),
		@InterceptorRef(value = "pageInterceptor", params = {"includeMethods", "doListByAppId"}),
		@InterceptorRef(value = "pageInterceptor", params = {"includeMethods", "selectDocProApproval"})
		}
)
@Controller
@Scope("prototype")
public class MyWorkAction extends CurdAction<Work> {

	private static final long serialVersionUID = 1L;

	private IdentityService identityService = IdFactory.getIdentityServiceFactory().getIdentityService();

	@Autowired
	private WorkService workService;
	@Autowired
	private AppAuthorityService appAuthorityService;
	@Autowired
	private HistTodoService histTodoService;
	@Autowired
	private TodoService todoService;
	@Autowired
	private AttachmentService attachmentService;
	@Autowired
	private ApplicationService applicationService;
	@Autowired
	private AppTypeService appTypeService;

	private String appId;
//	private String expand;
	private String type;
	private String appName;//fengjinshou 20151221 应用名
	private boolean hasDraftAuth;//fengjinshou 20151222 起草权限
	private String officeDocTypeIds = "";//fengjinshou 20151223 公文类型id
	private String officeDocTypeAppIds = "";//fengjinshou 20151223 公文类型应用
	private String locationFlag;//fengjinshou 20151224 数据删除后的跳转标记
	private String isShowDraft;//liujie add 20151224 是否显示起草按钮
	private String startorTitle;//fengjinshou 20151230 列表上显示的发起人表头

	@Override
	public void doList() {
		logger.debug("<进入>:doList方法");
		if(StringUtils.isNotBlank(entity.getWorkTitle()) && entity.getWorkTitle().equals("请输入标题名")){
			entity.setWorkTitle(null);
		}
		User user  = SessionUserUtil.getCurrentUser();
		entity.setStarter(user.getId());
		//fengjinshou 20151223 根据应用范围查找
		if(StringUtils.isNotBlank(officeDocTypeAppIds)){
			entity.setAppId(officeDocTypeAppIds);
		}
		list = workService.getAll(entity, entity.getWorkType());
	}

	/**
	 * 根据appId搜索
	 * @author 冯晋首
	 * @date   2015年12月21日 下午8:10:46
	 * @return
	 */
	public String doListByAppId() {
		logger.debug("<进入>:doListByAppId方法   根据appId搜索查询工作");
		if(appId!=null && !appId.equals("") && !appId.equals("null")){
			if(StringUtils.isNotBlank(entity.getWorkTitle()) && entity.getWorkTitle().equals("请输入标题名")){
				entity.setWorkTitle(null);
			}
			User user  = SessionUserUtil.getCurrentUser();
			entity.setStarter(user.getId());
			//fengjinshou 20151221
			entity.setAppId(appId);
			list = workService.getAll(entity, entity.getWorkType());
		}
		if(StringUtils.isNotBlank(appName) && appName.indexOf("借阅")!=-1){
			return "list_lending";
		}
		return "list_oneApp";
	}

	public String show(){
		logger.debug("<进入>:show方法");
		if("ticket".equalsIgnoreCase(type)){
			return "ticketShow";
		}else if("document".equalsIgnoreCase(type)){
			return "docShow";
		}
		return null;
	}

	/**
	 * 根据应用名跳转到单位应用列表页面
	 * @author 冯晋首
	 * @date   2015年12月23日 下午3:54:03
	 * @return
	 */
	public String showByAppName(){
		logger.debug("<进入>:showByAppName方法   根据应用名跳转到单位应用列表页面");
		//fengjinshou 20151221------------start
		String companyId = AppContext.getCurrentComId();
		if(StringUtils.isNotBlank(appName)){
			Application wfWork = applicationService.getAppName(appName.trim(), companyId);
			if(wfWork!=null){
				appId = wfWork.getAppId();
				if(StringUtils.isBlank(isShowDraft)||isShowDraft.equals("yes")){
					hasDraftAuth = verifyAuthority(appId);
				}
			}
		}
		//fengjinshou 20151221------------end
		if("ticket".equalsIgnoreCase(type)){
			return "ticketShow_oneApp";
		}else if("document".equalsIgnoreCase(type)){
			return "docShow_oneApp";
		}
		return null;
	}


	/**
	 * 跳转到借阅页面
	 * @author 冯晋首
	 * @date   2015年12月30日 下午5:55:46
	 * @return
	 */
	public String showLending(){
		logger.debug("<进入>:showLending方法   跳转到借阅页面");
		//fengjinshou 20151221------------start
		String companyId = AppContext.getCurrentComId();
		if(StringUtils.isNotBlank(appName)){
			Application wfWork = applicationService.getAppName(appName.trim(), companyId);
			if(wfWork!=null){
				appId = wfWork.getAppId();
				if(StringUtils.isBlank(isShowDraft)||isShowDraft.equals("yes")){
					hasDraftAuth = verifyAuthority(appId);
				}
			}
		}
		//fengjinshou 20151221------------end
		return "ticketShow_Lending";
	}



	/**
	 * 通过配制文件中的配制跳转到公文列表
	 * @author 冯晋首
	 * @date   2015年12月23日 上午9:45:06
	 * @return
	 */
	public String showOfficeDocByTypes(){
		logger.debug("<进入>:showOfficeDocByTypes方法  通过配制文件中的配制跳转到公文列表");
		String officeDocTypes = AppContext.getProperties("showOfficeDocTypes");
		if(StringUtils.isNotBlank(officeDocTypes)){
			if(officeDocTypes.indexOf(",")!=-1){
				String[] officeDocTypesArr =  officeDocTypes.split(",");
				for (String OfficeDocTypeStr : officeDocTypesArr) {
					List<AppType> types = appTypeService.findByName(OfficeDocTypeStr.trim());
					if(type!=null && types.size()>0){
						officeDocTypeIds+="'"+types.get(0).getTypeId()+"'"+",";
						Set<Application> appSet = types.get(0).getApps();
						for (Application app : appSet) {
							officeDocTypeAppIds+="'"+app.getAppId()+"'"+",";
						}
					}
				}
				if(StringUtils.isNotBlank(officeDocTypeIds)){
					officeDocTypeIds = officeDocTypeIds.substring(0, officeDocTypeIds.lastIndexOf(","));
				}
				if(StringUtils.isNotBlank(officeDocTypeAppIds)){
					officeDocTypeAppIds = officeDocTypeAppIds.substring(0, officeDocTypeAppIds.lastIndexOf(","));
				}
			}else{
				List<AppType> types = appTypeService.findByName(officeDocTypes.trim());
				if(type!=null && types.size()>0){
					officeDocTypeIds="'"+types.get(0).getTypeId()+"'";
					Set<Application> appSet = types.get(0).getApps();
					for (Application app : appSet) {
						officeDocTypeAppIds+="'"+app.getAppId()+"'"+",";
					}
				}
				if(StringUtils.isNotBlank(officeDocTypeAppIds)){
					officeDocTypeAppIds = officeDocTypeAppIds.substring(0, officeDocTypeAppIds.lastIndexOf(","));
				}
			}
		}
		return "showOfficeDocByTypes";
	}

	private boolean verifyAuthority(String appId){
		logger.debug("<进入>:verifyAuthority方法");
		//得到当前登录用户及其所在的部门和角色
		User user  = SessionUserUtil.getCurrentUser();
		List<Department> dep = identityService.getDepsOfUser(user.getId());
		List<Role> role = identityService.getRolesOfUser(user.getId());

		//得到该App所具有的权限
		String perAuthorIds = "";
		String deptAuthorIds = "";
		String roleAuthorIds = "";
		Map<String,AppAuthority> appAuthorityMap = appAuthorityService.getAuthorityMapByAppId(appId);
		if(appAuthorityMap!=null&&appAuthorityMap.size()>0){
			if(appAuthorityMap.get(AppAuthority.TYPE_PER)!=null){
				perAuthorIds = appAuthorityMap.get(AppAuthority.TYPE_PER).getAuthorityData();
				if(perAuthorIds!=null&&!perAuthorIds.isEmpty()&&perAuthorIds.contains(user.getId()))
					return true;
			}
			if(appAuthorityMap.get(AppAuthority.TYPE_DEPT)!=null){
				deptAuthorIds = appAuthorityMap.get(AppAuthority.TYPE_DEPT).getAuthorityData();
				if(dep!=null&&dep.size()>0){
					for(Department dm: dep){
						if(dm.getId()==null)continue;
						if(deptAuthorIds!=null&&!deptAuthorIds.isEmpty()&&deptAuthorIds.contains(dm.getId()))
							return true;
					}
				}
			}
			if(appAuthorityMap.get(AppAuthority.TYPE_ROLE)!=null){
				roleAuthorIds = appAuthorityMap.get(AppAuthority.TYPE_ROLE).getAuthorityData();
				if(role!=null&&role.size()>0){
					for(Role r:role){
						if(roleAuthorIds!=null&&!roleAuthorIds.isEmpty()&&roleAuthorIds.contains(r.getId()))
							return true;
					}
				}
			}
		}
		return false;
	}

	public String deldraftWorks(){
		logger.debug("<进入>:deldraftWorks方法");
		try{
			todoService.delWorks(delId);
			histTodoService.delWorks(delId);
		    attachmentService.delWorks(delId);
			workService.delWorks(delId);
			LogUtil.log(ModuleConstant.DOC_READY, LogUtil.ACTION_DELETE, LogUtil.RESULT_SUCCESS, "删除草稿工作、我的起草工作、草稿、我的起草");
		}catch(Exception e){
			logger.error("<错误>:删除失败",e);
			LogUtil.log(ModuleConstant.DOC_READY, LogUtil.ACTION_DELETE, LogUtil.RESULT_FAIL, "删除草稿工作、我的起草工作、草稿、我的起草");
		}
		//fengjinshou 20151224 从单个应用页面删除后的跳转
		if(StringUtils.isNotBlank(locationFlag) && "oneApp".equals(locationFlag)){
			return "delete_oneApp";
		}
		return "delete";
	}



/*	public String getExpand() {
		return expand;
	}
	public void setExpand(String expand) {
		this.expand = expand;
	}*/
	public String getAppId() {
		return appId;
	}
	public void setAppId(String appId) {
		this.appId = appId;
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public String getAppName() {
		return appName;
	}

	public void setAppName(String appName) {
		this.appName = appName;
	}

	public boolean isHasDraftAuth() {
		return hasDraftAuth;
	}

	public void setHasDraftAuth(boolean hasDraftAuth) {
		this.hasDraftAuth = hasDraftAuth;
	}

	public String getOfficeDocTypeIds() {
		return officeDocTypeIds;
	}

	public void setOfficeDocTypeIds(String officeDocTypeIds) {
		this.officeDocTypeIds = officeDocTypeIds;
	}

	public String getOfficeDocTypeAppIds() {
		return officeDocTypeAppIds;
	}

	public void setOfficeDocTypeAppIds(String officeDocTypeAppIds) {
		this.officeDocTypeAppIds = officeDocTypeAppIds;
	}

	public String getLocationFlag() {
		return locationFlag;
	}

	public void setLocationFlag(String locationFlag) {
		this.locationFlag = locationFlag;
	}

	public String getIsShowDraft() {
		return isShowDraft;
	}

	public void setIsShowDraft(String isShowDraft) {
		this.isShowDraft = isShowDraft;
	}

	public String getStartorTitle() {
		return startorTitle;
	}

	public void setStartorTitle(String startorTitle) {
		this.startorTitle = startorTitle;
	}

}
